<template>
  <div class="shopcar">
    <h1>购物车 一共{{ sum }}元</h1>

    <van-row v-for="item in $store.state.shopcar" :key="item._id">
      <van-col span="4">
        <input type="checkbox" v-model="result" :value="item" @change="check" />
      </van-col>
      <van-col span="20">
        <van-card
          :num="item.num"
          :price="item.price"
          :title="item.title"
          :thumb="item.pic"
        >
          <template #footer>
            <van-stepper v-model="item.num" @change="change" />
            <!-- <input type="text" v-model="item.num" /> -->
            <van-button size="mini" @click="del(index, item)">删除</van-button>
          </template>
        </van-card>
      </van-col>
    </van-row>

    <button @click="removeall">选中删除</button>

    <van-submit-bar :price="sum * 100" button-text="提交订单">
      <!-- <input type="checkbox" v-model="checked" /> -->
      <van-checkbox v-model="checked" @click="checkall">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
// import { Dialog } from "vant";
export default {
  data() {
    return {
      result: [],
      checked: false,
    };
  },
  mounted() {},
  methods: {
    change() {
      this.$store.commit("change");
    },
    checkall() {
      if (this.checked == true) {
        this.result = this.$store.state.shopcar;
      } else {
        this.result = [];
      }
    },
    check() {
      if (this.result.length == this.$store.state.shopcar.length) {
        this.checked = true;
      } else {
        this.checked = false;
      }
    },
    removeall() {
      this.$dialog
        .confirm({
          title: "标题",
          message: "确认删除选中的数据吗",
        })
        .then(() => {
          // on confirm

          this.$store.commit("removeall", this.result);
          this.result = [];
        })
        .catch(() => {
          // on cancel
        });
    },
    del(index, item) {
      this.$store.commit("del", index);
      this.result = this.result.filter((i) => {
        return i != item;
      }); //把不删的留下来
    },
  },
  components: {},
  computed: {
    sum() {
      let num = 0;
      this.result.forEach((item) => {
        num += item.price * item.num;
      });
      return num;
    },
  },
};
</script>

<style lang="scss" scoped>
.shopcar {
  padding-bottom: 80px;
}
</style>
